/**
 * 链表
 *
 * @author Kevin
 * @date 2018-11-22
 */
public class LinkedList<E> {

    /**
     * 头节点
     */
    private Node head;

    /**
     * 链表中的元素个数
     */
    private int size;

    public LinkedList() {
        this.head = null;
        this.size = 0;
    }

    /**
     * 获取链表中的元素个数
     */
    public int getSize() {
        return this.size;
    }

    /**
     * 链表是否为空
     */
    public boolean isEmpty() {
        return this.size == 0;
    }

    /**
     * 在链表头添加新的元素e
     */
    public void addFirst(E e) {
        this.head = new Node(e, this.head);
        this.size++;
    }

    /**
     * 在链表的index(0-based)位置添加新的元素e
     */
    public void add(int index, E e) {
        if (index < 0 || index > this.size) {
            throw new IllegalArgumentException("Add failed. Illegal index.");
        }

        if (index == 0) {
            addFirst(e);
        } else {
            Node prev = this.head;
            for (int i = 0; i < index - 1; i++) {
                prev = prev.next;
            }

            prev.next = new Node(e, prev.next);
            this.size++;
        }
    }

    /**
     * 在链表末尾添加新的元素e
     */
    public void addLast(E e) {
        add(this.size, e);
    }

    /**
     * 节点类
     */
    private class Node {
        public E e;

        public Node next;

        public Node() {
            this(null, null);
        }

        public Node(E e) {
            this(e, null);
        }

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        @Override
        public String toString() {
            return e.toString();
        }

    }

}
